from crum import get_current_user
from django.dispatch import receiver
from django.utils import timezone
from django_tenants.utils import schema_context

from apps.booking.signals import kiosk_check_in, client_check_in
from apps.communication.signals import provider_message, client_message
from apps.core.utils.fcm import send_notification
from apps.notification.models import ProviderNotificationSetting, ProviderNotification
from apps.notification.types import NotificationTypes
import logging

from apps.tenant.models import TrackingDeviceLogin
from apps.users.models import Provider


@receiver(kiosk_check_in)
def checked_in_though_kiosk(sender, instance, **kwargs):
    action = NotificationTypes.KIOSK_CHECK_IN
    dispatch(action, instance, client_initials=kwargs['initials'])

@receiver(client_message)
def add_client_message_notification(sender, instance, **kwargs):
    content = "{} {} has sent you a message".format(instance.client.first_name, instance.client.last_name)
    action = NotificationTypes.CLIENT_MESSAGES
    dispatch(action, instance.client, content=content)




@receiver(client_check_in)
def add_client_checked_in_notification(sender, instance, provider,client,  **kwargs):
    # client_names = [f"{client.first_name} {client.last_name}" for client in instance.clients.all()]
    # if len(client_names) > 1:
    #     last_client = client_names.pop()
    #     client_names_string = ", ".join(client_names)
    #     content = f"{client_names_string} and {last_client} have checked in"
    # elif len(client_names) == 1:
    #     content = f"{client_names[0]} has checked in"
    content = f'{client.first_name} {client.last_name} has checked in'
    setting = ProviderNotificationSetting.objects.all().first()
    if provider:
        with schema_context(provider.schema_name):
            action = None
            if setting.client_check_in:
                action = NotificationTypes.CLIENT_CHECK_IN
                notification = ProviderNotification.objects.create(
                    content=content,
                    notification_type=NotificationTypes.CLIENT_CHECK_IN.value,
                )

            if action == NotificationTypes.CLIENT_CHECK_IN and setting.client_check_in:
                push_notification(notification, action, instance, setting, client_initials=f'{client.first_name} {client.last_name}')



def dispatch(action, instance, **kwargs):
    if instance.is_provider:
        with schema_context(instance.schema_name):
            setting = ProviderNotificationSetting.objects.filter().first()
            if setting:
                if setting.client_check_in is True and action == NotificationTypes.CLIENT_CHECK_IN.value:
                    notification = ProviderNotification.objects.create(content=f'{kwargs["client_initials"]} has checked in ',
                    notification_type=NotificationTypes.CLIENT_CHECK_IN.value
                    )

                if action == NotificationTypes.KIOSK_CHECK_IN:
                    notification = ProviderNotification.objects.create(
                        content=f'{kwargs["client_initials"]} has checked in via kiosk',
                        notification_type=NotificationTypes.CLIENT_CHECK_IN.value
                        )

            if (action == NotificationTypes.CLIENT_CHECK_IN.value and setting.client_check_in) or action == NotificationTypes.KIOSK_CHECK_IN:
                push_notification(notification, action, instance, setting, client_initials=kwargs['client_initials'])
    elif instance.is_client:
        provider = Provider.objects.filter(id=instance.client.user_provider).first()
        with schema_context(provider.schema_name):
            setting = ProviderNotificationSetting.objects.filter().first()
            if setting:
                if setting.client_messages is True and action == NotificationTypes.CLIENT_MESSAGES:
                    notification = ProviderNotification.objects.create(
                        content=kwargs["content"],
                        notification_type=NotificationTypes.CLIENT_MESSAGES.value,
                    )
                if action == NotificationTypes.CLIENT_MESSAGES and setting.client_messages:
                    push_notification(notification, action, instance, setting,
                                      content=kwargs['content'])






    # else:
    #     push_notification(notification, action, instance, setting)


def push_notification(notification, action, instance, setting, **kwargs):
    logger = logging.getLogger(__name__)

    try:
        now = timezone.now().astimezone(tz=timezone.get_current_timezone())
        title = ''
        body = ''
        if action == NotificationTypes.KIOSK_CHECK_IN:
            title = 'Kiosk Check-in'
            body = f'{kwargs["client_initials"]} has checked in via Kiosk'
        if action == NotificationTypes.CLIENT_CHECK_IN:
            title = 'Client Check-in'
            body = f'{kwargs["client_initials"]} has checked in'
        if action == NotificationTypes.CLIENT_MESSAGES:
            title = 'Client Message'
            body = kwargs['content']

        devices = TrackingDeviceLogin.objects.filter()
        print(devices)
        for device in devices:
            device_id = device.device_id
            try:
                send_notification(device_id, title, body)
            except Exception as e:
                print(e)
                continue

        logger.debug("Notification sent for action: {}".format(str(action)))
    except Exception as ex:
        logger.exception('Failed to send push notification \n Got error:\n {}'.format(str(ex)))